<template>
    <NormalTable
        :refresh-action="'费用查询'"
        :tableColumns="tableColumns"
        :events="events"
        :tableAttribute="tableAttribute"
        :show-page="true"
        ref="childRef"
    >
    </NormalTable>
   
    <el-button-group class="bg">
        <el-space>
            <!-- <el-button class="btn" type="primary" :icon="Plus" @click="add"
                >增加</el-button
            > -->
            <AddBtn @click="add" :formData="paramData"></AddBtn>
            <!-- <el-button
                class="btn"
                type="primary"
                :icon="Delete"
                @click="onDelete"
                >删除</el-button
            > -->
            <DelBtn @click="onDelete"></DelBtn>
            <el-upload
                ref="uploadFeedetRef"
                action="/upload/importfeedet"
                :auto-upload="true"
                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                :limit="1"
                v-loading="importFeedetLoading"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-exceed="handleExceed"
                :on-success="handleSuccess"
            >
                <template #trigger>
                    <el-button type="primary">导入应收付费用</el-button>
                </template>
            </el-upload>

        </el-space>
    </el-button-group>
   

    <el-dialog
        v-model="dialogUpdateVisible"
        title="应收付费用维护"
        draggable
        destroy-on-close
        :center="true"
    >
        <NormalForm
            :formOptions="formOptions"
            :formItems="formItems"
            :formData="paramData"
            :createActionName="createActionName"
            :updateActionName="updateActionName"
            :rules="rules"
            @create="onAdded"
            @update="onUpdated"
            @close="onCloseDialog"
        >
        </NormalForm>
    </el-dialog>
    
</template>
<script setup lang="ts" name="Feedets">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox, genFileId } from 'element-plus';
import {
    forEach,
    forEachRight,
    includes,
    findIndex,
    omit
} from 'lodash';
import type { FeedetModel } from '@/common/types/business';
import {
    tableColumnDefault
} from '@/hooks/useTable';
import type { FormFieldItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    initObjectProperty,
    pickFormFromTable
} from '@/common/tools';
import type {
    FormRules, UploadInstance,
    UploadProps,
    UploadRawFile
} from 'element-plus';
import { useAppStore } from '@/store/app';
import { transFormatter, formatDate } from '@/common/tools';
import NormalForm from '@/components/forms/NormalForm.vue';
import NormalTable from '@/components/tables/NormalTable.vue';
const {
    cntrOwner,
    client,
    feecod,
    
    SelectOptionFeeInOut,
    SelectOptionYN,
    currency,
    
} = storeToRefs(useAppStore());

const childRef = ref<InstanceType<typeof NormalTable>>();
const tableAttribute = ref({
    id: 'feedets-table-feedets',
});

const uploadFeedetRef = ref<UploadInstance>();
const importFeedetLoading = ref(false);

const paramData = reactive<FeedetModel>({});

const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});
const rules = reactive<FormRules>({
    fee_unit_cod: [{ required: true, message: '请选择客户', trigger: 'blur' }],
    fee_owner: [{ required: true, message: '请选择成本中心', trigger: 'blur' }],
    fee_typ_cod: [
        { required: true, message: '请选择费用类型', trigger: 'blur' },
    ],

    cascaderfeecod: [
        { required: true, message: '请选择费目', trigger: 'blur' },
    ],
    amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
    currency_cod: [{ required: true, message: '请选择货币', trigger: 'blur' }],

    fee_tim: [{ required: true, message: '请选择计费日期', trigger: 'blur' }],
    fee_in_out: [
        { required: true, message: '请选择收付类型', trigger: 'blur' },
    ],
});
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'fee_unit_cod') {
        data = client.value;
    } else if (column['property'] === 'fee_cod') {
        data = feecod.value;
    } else if (column['property'] === 'fee_in_out') {
        data = SelectOptionFeeInOut.value;
    } else if (column['property'] === 'currency_cod') {
        data = currency.value;
    } else if (column['property'] === 'fee_owner') {
        data = cntrOwner.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'fee_unit_cod',
        label: '客户',
        fixed: 'left',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: client.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'fee_owner',
        label: '成本中心',
        fixed: 'left',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 150,
    },
    
    
    {
        ...tableColumnDefault,
        // isHidden: true,
        order: 5,
        prop: 'fee_cod',
        fixed: 'left',
        label: '费目',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: feecod.value,
        sortable: true,
        width: 80,
        noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'cntr',
        label: '箱号',
        fixed: 'left',
        formFieldItemType: 'input',
        sortable: true,
        width: 150,
    },

    {
        ...tableColumnDefault,
        order: 7,
        prop: 'fee_in_out',
        label: '收付',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionFeeInOut.value,
        sortable: true,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 8,
        prop: 'currency_cod',
        label: '币种',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: currency.value,
        sortable: true,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'fee_value',
        label: '单价',
        formFieldItemType: 'number',
        sortable: true,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 10,
        prop: 'fee_ton',
        label: '数量',
        formFieldItemType: 'number',
        sortable: true,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'amount',
        label: '金额',
        formFieldItemType: 'number',
        sortable: true,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'fee_nam',
        label: '计费人员',
        formFieldItemType: 'input',
        width: 120,
        sortable: true,
        noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 13,
        prop: 'fee_tim',
        label: '计费日期',
        formatter: formatDate,
        formFieldItemType: 'date',
        sortable: true,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'audit_id',
        label: '核销标识',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 15,
        prop: 'audit_finish_id',
        label: '核销完成标识',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 16,
        prop: 'fee_bill_no',
        label: '账单号',
        sortable: true,
        formFieldItemType: 'input',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 17,
        prop: 'pay_no',
        label: '付款码',
        sortable: true,
        formFieldItemType: 'input',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 18,
        prop: 'remark',
        label: '备注',
        sortable: true,
        width: 300,
    },
]);
const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);

const dialogUpdateVisible = ref(false);
const createActionName = ref('费用增加');
const updateActionName = ref('费用修改');


onMounted(() => {
    // childRef.value?.refresh();
    // tableHeight.value = window.innerHeight - tableMaxHeightAdjust;
    // alert(tableHeight.value);
});
const add = () => {
    initObjectProperty(paramData);
    dialogUpdateVisible.value = true;
};
const update = (row: any) => {
    paramData.cascaderfeecod = [row['fee_typ_cod'], row['fee_cod']];
    Object.assign(paramData, row);
    dialogUpdateVisible.value = true;
};
const onAdded = (data: FeedetModel) => {
    childRef.value?.tableData.unshift(data);
};
const onUpdated = (data: FeedetModel) => {
    const i = findIndex(childRef.value?.tableData, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        /* data.tax_amount = data.cost_amount! * data.tax_rate! * 0.01;
        data.amount = data.cost_amount! + data.tax_amount; */

        Object.assign(childRef.value?.tableData[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    }
};


const onDelete = async () => {
    const rows: Array<FeedetModel> = childRef.value?.tableRef?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    /* if (rows.length > 3) {
        ElMessage.info({
            message: '一次最多删除3条数据',
        });
        return;
    } */
    const ids = Array<number>();

    forEach(rows, (v: FeedetModel) => {
        ids.push(v.id as number);
    });

    const msg = '';
    const cr = await ElMessageBox.confirm(msg, '确认删除选中费用', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('费用删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(childRef.value?.tableData, (v: FeedetModel, i: number) => {
                if (includes(ids, v.id)) {
                    childRef.value?.tableData.splice(i, 1);
                }
            });
        }
    }
};

const beforeAvatarUpload = (rawFile: UploadRawFile) => {
    return new Promise<boolean>((resolve, reject) => {
        var reader = new FileReader();
        reader.readAsDataURL(rawFile);

        if (
            rawFile.type !== 'application/vnd.ms-excel' &&
            rawFile.type !==
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ) {
            ElMessageBox.alert('只能上传excel文件', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            importFeedetLoading.value = false;
            return reject(false);
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessageBox.alert('文件大小不能超过2M!', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            importFeedetLoading.value = false;
            return reject(false);
        }

        return resolve(true);
    });
};
const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadFeedetRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadFeedetRef.value!.handleStart(file);
};

const handleSuccess = (response: any) => {
    if (response.code > 0) {
        uploadFeedetRef.value!.clearFiles();
        ElMessageBox.alert(response.msg, '消息', {
            confirmButtonText: '确定',
            type: 'success',
        });
        // onRefresh();
        childRef.value!.tableData.length = 0;
        childRef.value!.tableData = response.obj;
    } else {
        ElMessageBox.alert(response.msg, '错误', {
            confirmButtonText: '确定',
            type: 'error',
        });
    }
    importFeedetLoading.value = false;
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
};
const events = {
     'row-dblclick': update
}

</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
